﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AMStudio.Common;
using AMStudio.DelegateDispather;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace AMStudio.UserInterface
{
    public partial class WorkorderForm : AWinFormShell
    {
        private bool stationAuto = false;

        public bool StationAuto
        {
            get { return stationAuto; }
            set { stationAuto = value; }
        }

        private DataTable dt;
        public WorkorderForm()
        {
            this.UIName = "WORKORDER";
            InitializeComponent();
        }

        private void navigationPanePanel1_Click(object sender, EventArgs e)
        {

        }

        public override bool ActivateUI()
        {


            this.UIName = this.Name;
            base.ActivateUI();
            //SetUserPrivilige();
            this.ShowDialog();

            return true;
        }

        protected override void Language_RfreshTag(LanguageItem item)
        {
            base.Language_RfreshTag(item);


            if (item.RelatedControl is ToolStrip)
            {
                string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                if (titles.Length>=9)
                {
                    this.toolStripButtonCreate.Text = this.toolStripButtonCreate.ToolTipText = titles[0];
                    this.toolStripButtonDelete.Text = this.toolStripButtonDelete.ToolTipText = titles[1];
                    this.toolStripButtonActivate.Text = this.toolStripButtonActivate.ToolTipText = titles[2];
                    this.toolStripButtonStop.Text = this.toolStripButtonStop.ToolTipText = titles[3];
                    this.toolStripButtonToolingCheck.Text = this.toolStripButtonToolingCheck.ToolTipText = titles[4];
                    this.toolStripButtonPrevious.Text = this.toolStripButtonPrevious.ToolTipText = titles[5];
                    this.toolStripButtonNext.Text = this.toolStripButtonNext.ToolTipText = titles[6];
                    this.toolStripButtonExit.Text = this.toolStripButtonExit.ToolTipText = titles[7];
                    this.Text = titles[8];
                }
            }


            if (item.RelatedControl is DataGridView)
            {
                string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                if (titles.Length >= 11)
                {
                    //this.nameDataGridViewTextBoxColumn.HeaderText = titles[0];
                    //this.productDataGridViewTextBoxColumn.HeaderText = titles[1];
                    //this.productNODataGridViewTextBoxColumn.HeaderText = titles[2];
                    //this.ColumnComments.HeaderText = titles[3];
                    //this.privilegeDataGridViewTextBoxColumn.HeaderText = titles[4];
                    //this.quantityDataGridViewTextBoxColumn.HeaderText = titles[5];
                    //this.finishedDataGridViewTextBoxColumn.HeaderText = titles[6];
                    //this.remainingDataGridViewTextBoxColumn.HeaderText = titles[7];
                    //this.startTimeDataGridViewTextBoxColumn.HeaderText = titles[8];
                    //this.endtimeDataGridViewTextBoxColumn.HeaderText = titles[9];
                    //this.passDataGridViewTextBoxColumn.HeaderText = titles[10];
                    //this.failDataGridViewTextBoxColumn.HeaderText = titles[11];

                }
            }

           
        }

        protected override void Language_InitializeControl(Control UIControl)
        {
            base.Language_InitializeControl(UIControl);


            if (UIControl is ToolStrip)
            {


                ToolStrip bar = UIControl as ToolStrip;
   
                      LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;

                      if ((item!=null) && ( item.Language[LanguageString]!=null))
                          
                      {
                          string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                          if (titles.Length >= 9)
                          {
                              this.toolStripButtonCreate.Text = this.toolStripButtonCreate.ToolTipText = titles[0];
                              this.toolStripButtonDelete.Text = this.toolStripButtonDelete.ToolTipText = titles[1];
                              this.toolStripButtonActivate.Text = this.toolStripButtonActivate.ToolTipText = titles[2];
                              this.toolStripButtonStop.Text = this.toolStripButtonStop.ToolTipText = titles[3];
                              this.toolStripButtonToolingCheck.Text = this.toolStripButtonToolingCheck.ToolTipText = titles[4];
                              this.toolStripButtonPrevious.Text = this.toolStripButtonPrevious.ToolTipText = titles[5];
                              this.toolStripButtonNext.Text = this.toolStripButtonNext.ToolTipText = titles[6];
                              this.toolStripButtonExit.Text = this.toolStripButtonExit.ToolTipText = titles[7];
                              this.Text = titles[8];
                          }
                      }
               
            }


            if (UIControl is DataGridView)
            {
                DataGridView bar = UIControl as DataGridView;

                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 11)
                    {
                        //this.nameDataGridViewTextBoxColumn.HeaderText = titles[0];
                        //this.productDataGridViewTextBoxColumn.HeaderText = titles[1];
                        //this.productNODataGridViewTextBoxColumn.HeaderText = titles[2];
                        //this.ColumnComments.HeaderText = titles[3];
                        //this.privilegeDataGridViewTextBoxColumn.HeaderText = titles[4];
                        //this.quantityDataGridViewTextBoxColumn.HeaderText = titles[5];
                        //this.finishedDataGridViewTextBoxColumn.HeaderText = titles[6];
                        //this.remainingDataGridViewTextBoxColumn.HeaderText = titles[7];
                        //this.startTimeDataGridViewTextBoxColumn.HeaderText = titles[8];
                        //this.endtimeDataGridViewTextBoxColumn.HeaderText = titles[9];
                        //this.passDataGridViewTextBoxColumn.HeaderText = titles[10];
                        //this.failDataGridViewTextBoxColumn.HeaderText = titles[11];
                    }
                }

            }
        

                
           
           
        }


        private void WorkorderForm_Load(object sender, EventArgs e)
        {
            dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Product", typeof(string));
            dt.Columns.Add("ProductNO", typeof(string));
            dt.Columns.Add("Status", typeof(string));
            dt.Columns.Add("Quantity", typeof(string));
            dt.Columns.Add("Finished", typeof(string));
            dt.Columns.Add("Remaining", typeof(string));
            //dt.Columns.Add("Name", typeof(string));
            //dt.Columns.Add("Name", typeof(string));

            User current = UserDB.CurrentLoginUser;
            switch (current.AuthorizationSet)
            {
                case 0:
                    this.toolStripButtonDelete.Enabled = true;
                    break;
                case 1:
                case 2:
                default:
                    this.toolStripButtonDelete.Enabled = false;
                    break;
            }
            base.SubscribeEvent("MANAGER_RET");
            this.RefreshUI();
        }
        public void RefreshUI()
        {
            dt.Clear();
            foreach (string k in WorkorderDB.woTags.Keys)
            {
                DataRow dr = dt.NewRow();
                dr["Name"] = WorkorderDB.woTags[k].Name;
                dr["Product"] = WorkorderDB.woTags[k].Product;
                dr["ProductNO"] = WorkorderDB.woTags[k].ProductNO;
                switch (WorkorderDB.woTags[k].Status)
                {
                    case 0:
                        dr["Status"] = "激活";
                        break;
                    case 1:
                        dr["Status"] = "空闲";
                        break;
                    case 2:
                        dr["Status"] = "完成";
                        break;
                }
                dr["Quantity"] = WorkorderDB.woTags[k].Quantity;
                dr["Finished"] = WorkorderDB.woTags[k].Finished;
                dr["Remaining"] = WorkorderDB.woTags[k].Remaining;
                dt.Rows.Add(dr);
            }
            DataView dv = dt.DefaultView;
            dv.Sort = "Status, Name ASC";
            dataGridViewX1.DataSource = dv;
        }
        private void buttonItem3_Click(object sender, EventArgs e)
        {
            try
            {
                NewWorkOrder nwo = new NewWorkOrder();
                nwo.ActivateUI();
                if (nwo.ShowDialog() == DialogResult.OK)
                {
                    if (!WorkorderDB.woTags.ContainsKey(nwo.Item.Name))
                    {
                        WorkorderDB.Add(nwo.Item);
                        this.RefreshUI();

                        string str = DateTime.Now.ToString() +
                        ",新建工单" + "," +
                        nwo.Item.Name + "," +
                        nwo.Item.Product + "," +
                        "partNr: " +
                        nwo.Item.ProductNO + "," +
                        "Quantity: " +
                        nwo.Item.Quantity.ToString() + "," +
                        "Pass: " +
                        nwo.Item.Pass.ToString() + "," +
                        "Fail: " +
                        nwo.Item.Fail.ToString() + "," +
                        nwo.Item.StartTime;
                        Logger.Write(str, "WORKORDER", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("WorkOrder Aready Exist");
                    }

                }
            }//try
            catch (Exception ex)
            {
                throw new Exception("NewWorkOrder", ex);
            }//catch
        }


        protected override void BackGroud_EventHandler(object sender, StationEventArgs e)
        {
            base.BackGroud_EventHandler(sender, e);
            if (e.From == "MANAGER")
            {
                switch (e.Command)
                {
                    case "ACTIVE_ORDER":
                        downLoadProgress = 100;
                        downloadFinished = true;
                        downloadSuccess = e.Status;
                        break;
                    case "REPORT_WORKORDER_DOWNLOAD":
                        downLoadProgress += 10;
                        break;
                    case "TOOLING_CHECK":
                        checkForm.RefreshStatus(e.Value as Dictionary<string, string>);
                        downloadFinished = true;
                        break;
                    case "ACTIVATE_NEW_WORKORDER_RET":
                        {

                        }
                        break;
                }
            }
        }
        private int downLoadProgress = 0;
        private string downLoadMessage = string.Empty;
        private bool downloadSuccess = false;
        private bool downloadFinished = false;
        ToolingCheckList checkForm;
        private void buttonItem5_Click(object sender, EventArgs e)
        {
            if (stationAuto)
            {
                System.Windows.Forms.MessageBox.Show("Machine in Auto mode!");
                return;
            }

            if (SelectedWorkOrder == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("Please select workorder first");
                return;
            }


            foreach (string k in WorkorderDB.woTags.Keys)
            {
                if (WorkorderDB.woTags[k].Status == 0)
                {
                    System.Windows.Forms.MessageBox.Show("Can not activate the other one!");
                    return;
                }
            }

            foreach (string k in WorkorderDB.woTags.Keys)
            {
                WorkorderDB.woTags[k].Status = 1;
                WorkorderDB.Update(WorkorderDB.woTags[k]);
            }
            WorkorderDB.woTags[SelectedWorkOrder].Status = 0;
            WorkorderDB.Update(WorkorderDB.woTags[SelectedWorkOrder]);
            WorkorderDB.woTags[SelectedWorkOrder].StartTime = DateTime.Now.ToString();
            string str = DateTime.Now.ToString() + 
                        ",激活工单" + "," +
                        WorkorderDB.woTags[SelectedWorkOrder].Name + "," +
                        WorkorderDB.woTags[SelectedWorkOrder].Product + "," +
                        "partNr: " +
                        WorkorderDB.woTags[SelectedWorkOrder].ProductNO + "," +
                        "Quantity: " +
                        WorkorderDB.woTags[SelectedWorkOrder].Quantity.ToString() + "," +
                        "Pass: " +
                        WorkorderDB.woTags[SelectedWorkOrder].Pass.ToString() + "," +
                        "Fail: " +
                        WorkorderDB.woTags[SelectedWorkOrder].Fail.ToString() + "," +
                        WorkorderDB.woTags[SelectedWorkOrder].StartTime;
            Logger.Write(str, "WORKORDER", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);

            downLoadProgress = 0;
            downloadSuccess = false;
            downloadFinished = false;
            downLoadMessage = string.Empty;
            SendMessage("ACTIVE_ORDER", null);
            DlgProgress dlgP = new DlgProgress();
            dlgP.SetMinimum(0);
            dlgP.SetMaximum(100);
            dlgP.SetTitle("Download product receipe to controllers and cells");
            dlgP.Show(this);
            dlgP.SetText("Downloading station settings......");
            for (int i = 0; i < 10; i++)
            {
                //if (downLoadProgress == 100)
                //{
                //    break;
                //}
                downLoadProgress += 10;
                dlgP.ReportStep(downLoadProgress);
                //dlgP.DoStep(downLoadProgress);
                //dlgP.SetText(downLoadMessage);
                Application.DoEvents();
                System.Threading.Thread.Sleep(100);
            }

            checkForm = new ToolingCheckList();
            //checkForm.Show(this);
            checkForm.ActivateUI();
            SendMessage("TOOLING_CHECK", checkForm.GetToolingCheckItem());
            while (true)
            {
                if (downloadFinished)
                    break;
                Application.DoEvents();
            }
            dlgP.Close();

            if (downloadSuccess)
            {
                //Do tooling check here;
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Down load work order failed");
            }

            this.RefreshUI();
            SendMessage("ACTIVATE_NEW_WORKORDER", WorkorderDB.woTags[SelectedWorkOrder].ProductNO);

        }


        private void dataGridViewX1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private string SelectedWorkOrder = string.Empty;
        private void dataGridViewX1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((e.RowIndex < 0) || (e.ColumnIndex < 0))
            {
                SelectedWorkOrder = string.Empty;
                return;
            }
            if (!string.IsNullOrEmpty(this.dataGridViewX1.Rows[e.RowIndex].Cells[0].Value.ToString()))
            {
                SelectedWorkOrder = this.dataGridViewX1.Rows[e.RowIndex].Cells[0].Value.ToString();
            }
            else
            {
                SelectedWorkOrder = string.Empty;
            }
        }

        private void dataGridViewX1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //foreach (DataGridViewRow dr in this.dataGridViewX1.Rows)
            //{
            //    FormatValue(dr);
            //}
        }
        private void FormatValue(DataGridViewRow dr)
        {
            //DataGridViewCell cell = dr.Cells["ColumnStatus"];

            //if (string.IsNullOrEmpty(cell.FormattedValue.ToString()))
            //    return;
            //string v = (string)cell.FormattedValue;


            //switch (v)
            //{
            //    case "0":
            //        dr.Cells["ColumnComments"].Value = "Active";
            //        break;
            //    case "1":
            //        dr.Cells["ColumnComments"].Value = "Waiting";
            //        break;
            //    case "2":
            //        dr.Cells["ColumnComments"].Value = "Finished";
            //        break;
            //}
        }

        private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e)
        {

        }

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            if (SelectedWorkOrder == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("Please select workorder first");
                return;
            }
            if (WorkorderDB.woTags[SelectedWorkOrder].Status == 0)
            {
                System.Windows.Forms.MessageBox.Show("You can't delete the active workorder");
                return;
            }
            else
            {
                if (System.Windows.Forms.MessageBox.Show("Do you want to delete it?", this.Text, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    string str = DateTime.Now.ToString() +
                        ",删除工单" + "," +
                        WorkorderDB.woTags[SelectedWorkOrder].Name + "," +
                        WorkorderDB.woTags[SelectedWorkOrder].Product + "," +
                        "partNr: " +
                        WorkorderDB.woTags[SelectedWorkOrder].ProductNO + "," +
                        "Quantity: " +
                        WorkorderDB.woTags[SelectedWorkOrder].Quantity.ToString() + "," +
                        "Pass: " +
                        WorkorderDB.woTags[SelectedWorkOrder].Pass.ToString() + "," +
                        "Fail: " +
                        WorkorderDB.woTags[SelectedWorkOrder].Fail.ToString() + "," +
                        WorkorderDB.woTags[SelectedWorkOrder].StartTime;
                    Logger.Write(str, "WORKORDER", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                    WorkorderDB.Delete(SelectedWorkOrder);
                }
            }
            this.RefreshUI();
            SendMessage("ACTIVE_ORDER", null);
        }

        private void btnToolingCheck_Click(object sender, EventArgs e)
        {
            checkForm = new ToolingCheckList();
            checkForm.ActivateUI();
            //checkForm.Show(this);
            SendMessage("TOOLING_CHECK", checkForm.GetToolingCheckItem());
        }

        private void btnCancelActivate_Click(object sender, EventArgs e)
        {

        }

        private void navigationBar1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonStop_Click(object sender, EventArgs e)
        {

            if (SelectedWorkOrder == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("Please select workorder first");
                return;
            }
            string str = DateTime.Now.ToString() + ",停止工单" + "," +
                WorkorderDB.woTags[SelectedWorkOrder].Name + "," +
                WorkorderDB.woTags[SelectedWorkOrder].Product + "," +
                "partNr: " +
                WorkorderDB.woTags[SelectedWorkOrder].ProductNO + "," +
                "Quantity: " +
                WorkorderDB.woTags[SelectedWorkOrder].Quantity.ToString() + "," +
                "Pass: " +
                WorkorderDB.woTags[SelectedWorkOrder].Pass.ToString() + "," +
                "Fail: " +
                WorkorderDB.woTags[SelectedWorkOrder].Fail.ToString() + "," +
                WorkorderDB.woTags[SelectedWorkOrder].StartTime;
            Logger.Write(str, "WORKORDER", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
            WorkorderDB.woTags[SelectedWorkOrder].Endtime = DateTime.Now.ToString();
            WorkorderDB.woTags[SelectedWorkOrder].Status = 1;
            WorkorderDB.Update(WorkorderDB.woTags[SelectedWorkOrder]);
            SendMessage("ACTIVE_ORDER", 1);
            this.RefreshUI();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButtonPrevious_Click(object sender, EventArgs e)
        {
            //bindingSource1.MovePrevious();
        }

        private void toolStripButtonNext_Click(object sender, EventArgs e)
        {
            //bindingSource1.MoveNext();
        }

        private void dataGridViewX1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //bindingSource1.Sort = "Name DESC";
        }
    }
}
